let userInfo ={}
let db = wx.cloud.database()
let content = ''
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    blogId: String,
    blog: Object
  },
  options: {
    styleIsolation: 'apply-shared'
  },

  /**
   * 组件的初始数据
   */
  data: {
    isShowModal: false,
    showLogin:false,
    content: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onComment(){
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: (res) => {
                userInfo = res.userInfo
                this.setData({
                  isShowModal: true
                })
              }
            })
          }else {
            this.setData({
              showLogin: true
            })
          }
        }
      })
    },
    onLoginSuccess(e){
      // userInfo = e.detail
      this.setData({
        showLogin: false
      },() => {
        this.setData({
          isShowModal: true
        })
      })
    },
    onLoginFail(){
      wx.showModal({
        title: '授权用户才能进行评价'
      })
    },
    onInput(e){
      this.setData({
        content: e.detail.value
      })
    },
    onSend() {
      const tmplId = 'It_sBikfSOy_PgnlfbHV1J4-KfWzISkuCEs2gpdACns'
      wx.requestSubscribeMessage({
        tmplIds: [tmplId],
        success: (res) => {
          if (res[tmplId] === 'accept') {
            wx.showToast({
              title: '订阅成功',
            })
            this._sendComment()
            wx.cloud.callFunction({
              name: 'sendMessage',
              data: {
                content,
                blogId: this.properties.blogId,
                user: userInfo.nickName
              }
            })
          }else{
            wx.showToast({
              title: '订阅失败',
            })
            this._sendComment()
          }
        }
      })
    },
    _sendComment(){
      content = this.data.content
      if (content.trim() == '') {
        wx.showToast({
          title: '请输入内容',
          icon: 'none'
        })
        return
      }
      wx.showLoading({
        title: '发送中',
      })
      db.collection('blog-comment').add({
        data: {
          content,
          blogId: this.properties.blogId,
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl,
          createTime: db.serverDate()
        }
      }).then(() => {
        wx.hideLoading()
        wx.showToast({
          title: '发送成功',
        })
        this.setData({
          isShowModal: false,
          content: ''
        })
        this.triggerEvent('commentComplete')
        wx.navigateTo({
          url: '/pages/blogComment/blogComment?blogId='+this.properties.blogId,
        })
      })
    }
  }
})
